<?php
/**
 * User: 昊天||597767865@qq.com
 * Date: 2019/8/27
 * Time: 10:06
 */
namespace backend\controllers;
use backend\models\Module;
use Yii;
class ModuleController extends BaseController
{
    public function actionIndex()
    {
        $pageSize = $this->pageSize;
        return $this->render('index',compact('pageSize'));
    }

    /**
     * 列表
     */
    public function actionList()
    {
        $page = intval(input('page'));
        $limit = intval(input('limit'));
        $model = Module::find();
        $data = $model
            ->orderBy('sort desc,id desc')
            ->offset(($page-1)*$limit)
            ->limit($limit)
            ->asArray()->all();
        $count = $model->count();
        $this->api(0,'success',$count,$data);
    }

    public function actionCreate()
    {
        if(Yii::$app->request->isPost){
            $data = input();
            $module = new Module();
            $data['create_time'] = time();
            $data['create_user'] = Yii::$app->user->identity->name;
            unset($data[Yii::$app->request->csrfParam]);
            $arr['Module'] = $data;
            if($module->load($arr) && $module->save()){
                $this->json('200','添加成功');
            }else{
                $this->json(100,array_values($module->getFirstErrors())[0]);
            }
        }
        return $this->render('create');
    }

    /**
     * 修改
     * @return string
     */
    public function actionEdit()
    {
        if(Yii::$app->request->isPost){
            $data = input();
            unset($data[Yii::$app->request->csrfParam]);
            $id = intval($data['id']);
            $module = Module::findOne($id);
            $arr['Module'] = $data;
            if($module->load($arr) && $module->save()){
                $this->json('200','修改成功');
            }else{
                $this->json(100,array_values($module->getFirstErrors())[0]);
            }
        }
        $id = (int)input('id');
        $model = Module::findOne($id);
        return $this->render('edit',compact('model'));
    }

    /**
     * 更改状态
     */
    public function actionStatus()
    {
        $id = (int)input('id');
        $status = (int)input('status');
        $user = Module::findOne($id);
        $user->is_show = $status==1?2:1;
        if($user->save()){
            $this->json(200,'状态更改成功');
        }
        $this->json(100,array_values($user->getFirstErrors())[0]);
    }

    public function actionDel()
    {
        $id = (int)input('id');
        $model = Module::findOne($id);
        if($model->delete()){
            $this->json(200,'删除成功');
        }
        $this->json(100,'删除失败');
    }

    public function actionBatchDel()
    {

    }
}
